﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ARSys.Entity;

namespace Wicresoft.Task.ARNotice
{
    abstract class EmailTemplate
    {
        protected Email armail;
        protected ARSysContext dc;

        public EmailTemplate(Email armail, ARSysContext dc, params object[] entities)
        {
            this.armail = armail;
            this.dc = dc;

            var templateContext = GetTemplate(TemplateName, "Email.xslt");

            SimpleTemplateEngine engine = new SimpleTemplateEngine();
            engine.ProceedTemplate(templateContext, entities);

            Body = engine.ProcessedText.ToString();
            Subject = GetTitle(Body);
        }

        private string GetTemplate(string name, string traslator)
        {
            var xmlFile = Path.Combine("Template", name);
            var xsltFile = Path.Combine("Template", traslator);

            // Temporary disable xslt transform until it completes
            //return XmlUtil.Transform(xmlFile, xsltFile);
            return File.ReadAllText(xmlFile);
        }

        private string GetTitle(string template)
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(template);
            return xml.SelectSingleNode("html/head/title").InnerXml;
        }

        public virtual string Subject { get; protected set; }
        public virtual string Body { get; protected set; }

        public abstract string[] To { get; }
        public virtual string[] Cc { get { return null; } }

        // If Bcc is defined in schedule.xml, we sent the mail bcc to the specific person(s)
        public virtual string[] Bcc
        {
            get
            {
                if (EmailFactory.Bag.Bcc != null)
                    return EmailFactory.Bag.Bcc.Split(';');
                else
                    return null;
            }
        }

        // By default, we set mail reply to as mail to
        //  in order to prevent no one reply system email by incident
        public virtual string[] ReplyTo { get { return To; } }
        public virtual MailPriority Priority { get { return MailPriority.Normal; } }

        protected virtual string TemplateName { get { return GetType().Name + ".htm"; } }



        protected string[] TryGetReceptions(string cil)
        {
            var source = from ppl in dc.People
                         where ppl.CIL == cil && ppl.ProfileStatus == 1
                         select ppl.Email;
            return source.ToArray();
        }
    }
}
